package middleware

import (
	"fmt"
	"gin-cli/library/auth"
	config2 "gin-cli/utils/config"
	"github.com/gin-gonic/gin"
	"log"
	"time"
)

func respondWithError(code int, message string, c *gin.Context) {

	resp := map[string]string{"error": message}

	c.JSON(code, resp)

	c.Abort()

}

func CheckApiToken () gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Header["Token"] == nil {
			respondWithError(401, "Not api token.", c)
			return
		}
		token := c.Request.Header["Token"][0]
		key := config2.Get("config.apiTokenKey").(string)
		rebuildTime := config2.Get("config.apiTokenRebuildTime").(int)

		tokenInfo, exp, err := auth.JwtDecode(token, key)
		if err != nil {
			fmt.Println(err)
		}

		if time := time.Now().Unix(); int(exp - time) < rebuildTime {
			log.Println("rebuilding")
			newToken, err := auth.JwtEncode(tokenInfo, key)
			if err != nil {
				fmt.Println("token 续期失败")
			}
			token = newToken
		}
		c.Writer.Header().Set("token", token)

		c.Set("tokenInfo", tokenInfo)
		c.Next()
	}
}
